package com.lanhai.ads.controller;

import com.alibaba.fastjson.JSONObject;
import com.lanhai.ads.model.AgvStateInfo;
import com.lanhai.ads.model.AgvTransferLog;
import com.lanhai.ads.service.AgvLogService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Api(tags = "车辆对接记录查询接口")
@Slf4j
@RestController
public class AgvLogController {
//    @GetMapping
//    public String index(){
//        return "FnIgvStatistis application is running.";
//    }

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    AgvLogService agvLogService;


    @ApiOperation("查询对接记录")
    @PostMapping(value = "/transferlog/list", produces = MediaType.APPLICATION_JSON_VALUE)
    public List<AgvTransferLog> listTransferLog(@RequestBody AgvTransferLog agvTransferLog) {
        log.info(agvTransferLog.toString());
        return agvLogService.listTransferLog(agvTransferLog);
    }

    /**
     * IGV实时状态数据查询
     * 从redis中获取所有的小车缓存数据
     *
     * @return
     */
    @GetMapping("/agv/mapinfos")
    public List<AgvStateInfo> mapinfos() {

        //获取所有小车的缓存key
        Set<String> keys = redisTemplate.keys("agvbean_*");
        //根据获取的key获取小车缓存数据
        List<String> strings = redisTemplate.opsForValue().multiGet(keys);

        List<AgvStateInfo> list = strings.stream().map(item -> {
                    //组装成需要的数据格式
                    AgvStateInfo agvStateInfo = JSONObject.parseObject(item, AgvStateInfo.class);
                    agvStateInfo.setId(agvStateInfo.getAgvId());
                    agvStateInfo.setLastState(agvStateInfo.getLastReceive() != null ? agvStateInfo.getLastReceive().getCode() : null);
                    return agvStateInfo;
                }
        ).collect(Collectors.toList());
        return list;
    }


}
